import { BASE_SETTING } from '@/common/constant'

export const useLocalStorageM = () => {
  const projectName = BASE_SETTING.PROJECT_NAME

  /**
   * 设置本地缓存值
   * @param key
   * @param data
   */
  const setItem = (key: string, data: any) => {
    const formatKey = `${projectName}:${key}`

    try {
      const d = JSON.stringify(data)
      window.localStorage.setItem(formatKey, d)
    } catch (e) {
      window.localStorage.setItem(formatKey, data)
    }
  }

  /**
   * 获取本地缓存值
   * @param key
   */
  const getItem = (key: string) => {
    const formatKey = `${projectName}:${key}`
    const data = window.localStorage.getItem(formatKey)

    try {
      return data ? JSON.parse(data) : ''
    } catch (e) {
      return data
    }
  }

  /**
   * 删除本地缓存
   * @param key
   */
  const removeItem = (key: string) => {
    const formatKey = `${projectName}:${key}`
    window.localStorage.removeItem(formatKey)
  }

  return {
    setItem,
    getItem,
    removeItem
  }
}
